package edu.ruc.cluster.host;

import java.io.IOException;
import edu.ruc.cluster.util.AbstractInteractiveCommand;
import edu.ruc.cluster.util.Const;

/**
 * 2012-12-4
 * This class is used for adding ip and host name in /etc/hosts, however, should always login as root, the reason is
 * that shell will firstly execute "echo /etc/hosts", with sudo, and then >> /etc/hosts, but this also needs sudo 
 * @author deke
 * Modified on 2012-12-6
 * Try another way, copy the original /etc/hosts and ~/Const.HOSTS_ADD_PATH to ~/Const.HOSTS_DES_PATH
 * Then copy ~/Const.HOSTS_DES_PATH to /etc/hosts
 */
public class HostsAddCmd extends AbstractInteractiveCommand {

	public HostsAddCmd(String host, String passwd){
		super(host, passwd);
	}
	@Override
	public void interactProcess(String cmd) {
		// TODO Auto-generated method stub
		String[] commands = cmd.split("xxx");
		
		try{
			int count = 1;
			for(int i = 0 ; i < commands.length ; i ++){
				writor.write((commands[i] + "\n").getBytes());
				writor.flush();
				
		    	char[] cbuf = new char[1024];			
				int ret = reader.read(cbuf);
				
				while(ret != -1){
					String info = new String(cbuf, 0, ret);
					System.out.print(info);
					if(info.contains("[sudo] password")){
						writor.write((getPasswd() + "\n").getBytes());
				    	writor.flush();
					}else if(info.contains("[" + getUser()+ "@")){						
						if(count == 0){
							break;
						}
						count --;
					}
					ret = reader.read(cbuf);
				}
			}
			
		}catch(IOException e){
			logHandler.error(this.getClass().getSimpleName() + e.getMessage(), e);
		}
	}
	public void addhostsfile(){
		
		/*
		 * Firstly, cat the original /etc/hosts to ~/Const.HOSTS_DES_PATH
		 * Then, cat ~/Const.HOSTS_ADD_FILE to ~/Const.HOSTS_DES_PATH
		 * Then, move /etc/hosts as /etc/hosts-backup
		 * Finally, copy ~/Const.HOSTS_DES_PATH as /etc/hosts
		 */
		String cmd1 = "cat /etc/hosts >> ~/" + Const.HOSTS_DES_PATH;
		String cmd2 = "cat ~/" + Const.HOSTS_ADD_FILE + " > ~/" + Const.HOSTS_DES_PATH;
		String cmd3 = "sudo mv /etc/hosts /etc/hosts-backup";
		String cmd4 = "sudo cp ~/" + Const.HOSTS_DES_PATH + " /etc/hosts";
		dealcmd(cmd2 + "xxx" + cmd1 + "xxx" + cmd3 + "xxx" + cmd4);
	}
	
	public static void main(String[] args){		
		
		String host = "deke@dlnode26";
		String passwd = "111111";
		HostsAddCmd ha = new HostsAddCmd(host, passwd);
		ha.addhostsfile();
	}
}
